package com.zhongli.devplatform.controller.teacher;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sun.org.apache.regexp.internal.RE;
import com.zhongli.devplatform.bean.Res;
import com.zhongli.devplatform.bean.SecurityHelper;
import com.zhongli.devplatform.enums.GradeTypeEnum;
import com.zhongli.devplatform.enums.UserType;
import com.zhongli.devplatform.po.common.ReadClazzOperationPO;
import com.zhongli.devplatform.po.common.ReadClazzPO;
import com.zhongli.devplatform.po.common.ReadGradePO;
import com.zhongli.devplatform.po.common.ReadTeachClazzPO;
import com.zhongli.devplatform.po.view.ViewTeacherToSchoolPO;
import com.zhongli.devplatform.po.view.ViewUserPO;
import com.zhongli.devplatform.po.view.ViewUserToSchoolPO;
import com.zhongli.devplatform.query.teacher.TeacherQuery;
import com.zhongli.devplatform.service.imp.common.ReadClazzOperationService;
import com.zhongli.devplatform.service.imp.common.ReadClazzService;
import com.zhongli.devplatform.service.imp.common.ReadGradeService;
import com.zhongli.devplatform.service.imp.common.ReadTeachClazzService;
import com.zhongli.devplatform.service.imp.im.IMRestAPIService;
import com.zhongli.devplatform.service.imp.user.ReadUserService;
import com.zhongli.devplatform.service.imp.view.ViewTeacherToService;
import com.zhongli.devplatform.service.imp.view.ViewUserService;
import com.zhongli.devplatform.service.imp.view.ViewUserToSchoolPOService;
import com.zhongli.devplatform.utils.BeanCopierUtil;
import com.zhongli.devplatform.utils.StringUtils;
import com.zhongli.devplatform.vo.common.ClazzVO;
import com.zhongli.devplatform.vo.teacher.SchoolTeacherVO;
import com.zhongli.devplatform.vo.teacher.TeacherInfoVO;
import com.zhongli.devplatform.vo.teacher.TeacherVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @author wy
 * @since 2020/7/30
 */
@Api(tags = "老师app接口",description = "老师操作接口...")
@RestController
@RequestMapping("/api/teacher")
public class TeacherController {

    @Autowired
    private ViewUserService viewUserService;

    @Autowired
    private ViewTeacherToService viewTeacherToService;

    @Autowired
    private ViewUserToSchoolPOService userToSchoolPOService;

    @Autowired
    private ReadTeachClazzService teachClazzService;

    @Resource
    private ReadClazzOperationService clazzOperationService;

    @Autowired
    private ReadClazzService clazzService;

    @Autowired
    private ReadGradeService gradeService;

    @Autowired
    private ReadUserService userService;

    /**
     * 查询老师的粉丝列表
     * @return 结果
     */
    /*@ApiOperation("查询老师的粉丝列表数量")
    @GetMapping("/getAllFans")
    public Res getFansInfo(){
        Integer currentUserId = SecurityHelper.getCurrentUserId();
        List<ReadUserPO> data = userService.getCurrentTeacherFans(currentUserId);
        return Res.ok(data.size());
    }*/

    /**
     * 查询老师所任课的班级列表
     * @param gradeId 年级id
     * @param status  状态：true有邀请码的班级，false没有邀请码的班级
     * @return
     */
    @ApiOperation("查询老师所任课的班级列表")
    @GetMapping("/currentTeacherClazzList")
    public Res<List<ClazzVO>> currentTeacherClazzList(@RequestParam(value = "gradeId",required = false) Integer gradeId,@RequestParam("status") Boolean status){
        Integer currentUserId = SecurityHelper.getCurrentUserId();
        List<ReadTeachClazzPO> teachers = teachClazzService.list(new QueryWrapper<ReadTeachClazzPO>().eq("teacher_id", currentUserId));
        if (teachers.isEmpty()){
            return new Res<>(1,"暂无任课班级");
        }
        List<Integer> clazzIds = teachers.stream().map(ReadTeachClazzPO::getClazzId).collect(Collectors.toList());
        List<ReadClazzPO> clazzPOS;
        if(gradeId != null){
            clazzPOS = clazzService.list(new QueryWrapper<ReadClazzPO>().eq("grade_id",gradeId).in("id",clazzIds));
        }else {
            clazzPOS = clazzService.list(new QueryWrapper<ReadClazzPO>().in("id",clazzIds));
        }
        List<ClazzVO> clazzVOS = BeanCopierUtil.copy(clazzPOS, ClazzVO.class);
        assert clazzVOS != null;
        if (status){
            clazzVOS = clazzVOS.stream().filter(item -> StringUtil.isNotBlank(item.getInvitationCode())).collect(Collectors.toList());
            clazzVOS.forEach(item -> {
                ReadGradePO gradePO = gradeService.getById(item.getGradeId());
                String[] strings = gradePO.getGradeName().split("/");
                item.setGradeName(strings[0]);
                item.setGradeType(GradeTypeEnum.values()[gradePO.getGradeType()]);
            });
        }else {
            clazzVOS = clazzVOS.stream().filter(item -> StringUtil.isBlank(item.getInvitationCode())).collect(Collectors.toList());
        }
        return Res.ok(clazzVOS);
    }

    /**
     * 根据当前学生用户 查询所在年级的所有老师
     * @return 结果
     */
    @ApiOperation("根据当前学生用户 所选学校 - 老师教授科目 - 昵称查询老师")
    @GetMapping("/getAllTeacher")
    public Res getAllTeacher(
            @RequestParam(required = false) String nickName,
            @RequestParam(required = false) String teacherType,
            @RequestParam(required = false) Integer schoolType){
        //当前用户所在学校的所有老师
        List<ViewUserToSchoolPO> userToSchoolPOS = userToSchoolPOService.list(new QueryWrapper<ViewUserToSchoolPO>()
                .eq(schoolType !=null,"school_id", schoolType)
                .eq("category",UserType.Teacher.getCode()));
        List<Integer> teacherIds = userToSchoolPOS.stream()
                .map(ViewUserToSchoolPO::getId)
                .collect(Collectors.toList());
        if (teacherIds.isEmpty()) {
            return Res.ok(new ArrayList<ViewUserPO>());
        }
        List<ViewUserPO> data = viewUserService.list(new QueryWrapper<ViewUserPO>()
                //.eq("category",UserType.Teacher.getCode())
                .in("user_id",teacherIds)
                .like(!StringUtils.isBlank(nickName),"nick_name",nickName)
                .eq(!StringUtils.isBlank(teacherType),"teacher_type",teacherType)
        );
        return Res.ok(data);
    }

    public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }


    /**
     * 查询所在学校的所有老师
     * @return 结果
     */
    @GetMapping("/getSchoolTeacher")
    public Res teacherListBySchool(@RequestParam(value = "gradeId",required = false) Integer gradeId){
        Integer userId = SecurityHelper.getCurrentUserId();
        ViewTeacherToSchoolPO user = viewTeacherToService.getById(userId);
        List<ViewTeacherToSchoolPO> teacherToSchoolPOS;
        //当前用户所在学校的所有老师
        if (gradeId == null){
            teacherToSchoolPOS = viewTeacherToService.list(new QueryWrapper<ViewTeacherToSchoolPO>()
                    .eq("school_id", user.getSchoolId()));
        }else {
            teacherToSchoolPOS = viewTeacherToService.list(new QueryWrapper<ViewTeacherToSchoolPO>()
                    .eq("school_id", user.getSchoolId())
                    .eq("grade_id",gradeId));
        }
        List<SchoolTeacherVO> schoolTeacherVOS = BeanCopierUtil.copy(teacherToSchoolPOS, SchoolTeacherVO.class);
        assert schoolTeacherVOS != null;
        if (!schoolTeacherVOS.isEmpty()){
            schoolTeacherVOS = schoolTeacherVOS.stream().filter(distinctByKey(SchoolTeacherVO::getId)).collect(Collectors.toList());
        }
        schoolTeacherVOS = schoolTeacherVOS.stream().filter(item -> !item.getId().equals(userId)).collect(Collectors.toList());
        return Res.ok(schoolTeacherVOS);
    }

    @ApiOperation("获取老师列表")
    @GetMapping("/list")
    public Res list(@ModelAttribute TeacherQuery query){
        QueryWrapper<ViewUserPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(!StringUtils.isBlank(query.getAccountNum()),"account_num",query.getAccountNum());
        queryWrapper.like(!StringUtils.isBlank(query.getNickName()),"nick_name",query.getNickName());
        queryWrapper.eq("category",UserType.Teacher.getCode());
        List<ViewUserPO> userPOS = viewUserService.list(queryWrapper);
        List<TeacherVO> teacherVOS = BeanCopierUtil.copy(userPOS, TeacherVO.class);
        return Res.ok(teacherVOS);
    }


    @ApiOperation("获取老师个人信息")
    @GetMapping("/getCurrentTeacherInfo")
    public Res getCurrentTeacherInfo(){
        Integer currentUserId = SecurityHelper.getCurrentUserId();
        ViewUserPO viewUserPO = viewUserService.getOne(new QueryWrapper<ViewUserPO>().eq("user_id",currentUserId));
        TeacherInfoVO infoVO = BeanCopierUtil.copy(viewUserPO, TeacherInfoVO.class);
        assert infoVO != null;
        infoVO.setId(viewUserPO.getUserId());
        int count = clazzOperationService.list(new QueryWrapper<ReadClazzOperationPO>().eq("create_user_id", currentUserId)).size();
        infoVO.setArrangeOperation(count);
        return Res.ok(infoVO);
    }

    @ApiOperation("获取老师是否是班级的班主任")
    @GetMapping("/getIsAdminTeacher/{id}")
    public Res getIsAdminTeacher(@PathVariable("id") Integer id){
        Integer userId = SecurityHelper.getCurrentUserId();
        ReadTeachClazzPO one = teachClazzService.getOne(new QueryWrapper<ReadTeachClazzPO>()
                .eq("teacher_id", userId)
                .eq("clazz_id", id)
                .eq("is_admin_teacher", true));
        if (!Objects.isNull(one)){
            return Res.ok(true);
        }
        return Res.ok(false);
    }

    @ApiOperation("导入当前老师用户到im系统")
    @PostMapping("/importTeacherImUserId")
    public Res importTeacherImUserId(){
       return userService.importTeacherImUserId();
    }

}
